package com.hzjh.base.ext.ai

import com.google.ai.client.generativeai.Chat
import com.google.ai.client.generativeai.GenerativeModel
import com.hzjh.base.ext.BuildConfig
import com.hzjh.base.log.JHLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object AiUtils {
    private val generativeModel by lazy {
        GenerativeModel(
            // For text-only input, use the gemini-pro model
            modelName = "gemini-pro",
            // Access your API key as a Build Configuration variable (see "Set up your API key" above)
            apiKey = BuildConfig.AIapiKey
        )
    }
    private val aiChat by lazy { getChat() }
    private fun getModel(): GenerativeModel{
        return generativeModel
    }

    private fun getChat(): Chat {
        return getModel().startChat()
    }

    fun sendMsg(viewModelScope: CoroutineScope,msg:String,aiCallBack: ((String) -> Unit)?=null){
        try {
            viewModelScope.launch(context = Dispatchers.Main) {
                val response = withContext(Dispatchers.IO) {
                    aiChat.sendMessage(msg)
                }
                JHLogger.d(response.text ?: "")
                aiCallBack?.invoke(response.text ?: "")
            }
        }catch (e:Exception){
            JHLogger.e(e.toString())
        }
    }
}